<!-- c_check.ftl 盘点单 -->
var CCheck = {
    u: '/cCheck'
    , uList: '/cCheck/list'
    , uEdit: '/cCheck/edit'
    , uDel: '/cCheck/delete'
    , uEditDetail: '/cCheckDetail/list'
    , unitArr: []
    , checkStatus: 0
    , editIndex: -1
    ,checkId:0
};

CCheck.dg = function () {
    var grid = new $yd.DataGrid(this.dtable);
    // grid.onDblClickRow = function (index,row) {
    //     CCheck.detail(row['id']);
    // };
    grid.url = CCheck.uList;
    grid.rownumbers = true;
    grid.singleSelect = true;
    grid.onClickRow = function (index,row) {
        $(this).datagrid('unselectRow', index);
        CCheck.checkStatus =row['status'];
        if (CCheck.checkStatus !=0) {
            document.getElementById("checkGoodsBtn").style.display="none";
        }
        if (CCheck.checkStatus ==0) {
            document.getElementById("checkGoodsBtn").style.display="block";
        }
        CCheck.checkId = row['id']
        // CCheck.detail(row['id']);
        CCheck.goodsTable.datagrid("reload", {
            checkId: row.id,

        });
        
    };
    grid.columns = [[
        {field: 'id', checkbox: true},
        {field: 'ctime', title: '盘点时间', width: 80,halign:'center',align:'center'},
         {field: 'code', title: '盘点单号', width: 80,halign:'center',align:'center'}
        , {field: 'houseName', title: '仓库', width: 80,halign:'center',align:'center'}
        , {field: 'totalNum', title: '盘点商品数', width: 80,halign:'center',align:'center'}
        , {
            field: 'status', title: '状态', width: 50,halign:'center',align:'center', formatter: function (value) {
                if (value == 0) {
                    return '<label class="label label-success">待校正</label>';
                } else if(value == 1) {
                    return '<label class="label label-default">已校正</label>';
                } else if(value == 2) {
                    return '作废';
                }
            }
        }
        , {field: 'username', title: '盘点人', width: 80,halign:'center',align:'center'}
    ]];
    grid.loadGrid();
};

CCheck.dg.getOne = function () {
    var sels = CCheck.dg.getSels();
    if (sels.length === 1) {
        return sels[0];
    }
    return null;
};
CCheck.dg.getSels = function () {
    return CCheck.dtable.datagrid('getSelections');
};
CCheck.print = function () {
    var rows = CCheck.dtable.datagrid('getChecked');
    if(rows.length == 0) {
        $yd.alert("选择记录");
        return;
    }
    var id = rows[0].id
    parent.inv.OpenPage("/cCheckDetail/printPage?checkId=" + id, "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "<span class=\"menu-text\"> 打印盘点单</span>\n" +
        "<b class=\"arrow \"></b>", true)
}
CCheck.remove = function() {
    var rows = CCheck.dtable.datagrid('getChecked');
    if(rows.length == 0) {
        $yd.alert("选择记录");
        return;
    }
    var ids = [];
    for(var i=0;i<rows.length; i++) {
        if(rows[i].status == 1) {
            $yd.alert("已校正无法删除");
            return;
        }
        ids.push(rows[i].id);
    }
    $.get(CCheck.uDel, {ids: ids}, function (data) {
        if($yd.isEmpty(data.message) || data.message == "操作成功") {
            $yd.alert("删除成功", function () {
                CCheck.search();
            });
        } else {
            $yd.alert(data.message);
        }
    });
};
// 处理按钮
CCheck.btn = function () {
    var sb = new $yd.SearchBtn($(CCheck.obtn));
    sb.create('print yellow', '打印', CCheck.print);
    sb.create('repeat red', '重置', CCheck.reset);
    // sb.create('refresh', '刷新', CCheck.refresh);
    // sb.create('edit', '编辑', CCheck.edit);
    sb.create('remove', '删除', CCheck.remove);
    sb.create('plus', '新增', CCheck.plus);
    // sb.create('search', '查询', CCheck.search);
};

// 重置
CCheck.reset = function () {
    $("form.search-form").form('clear');
    CCheck.dtable.datagrid("unselectAll");
    CCheck.dtable.datagrid('load', CCheck.sform.serializeObject());
};

//
CCheck.edit = function () {
    var sel = CCheck.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    CCheck._edit(sel['id'])
};
CCheck._edit = function (id) {
    $yd.win.create('编辑盘点单', CCheck.uEdit + '?id=' + id).open(function (that, $win) {
            $yd.get(CCheck.u + "/" + id, function (data) {
                $win.find('form').form('load', data);
            })
        }, function (that, $win) {
            $yd.form.create($win.find('form')).url(CCheck.u).submit(function () {
                that.close();
                CCheck.refresh();
            });
        }
    );
};
// 详情
CCheck.detail= function(checkId) {
    parent.inv.OpenPage("/cCheckDetail?checkId=" + checkId, "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "<span class=\"menu-text\"> 盘点单详情</span>\n" +
        "<b class=\"arrow \"></b>",true)
}

//新增
CCheck.plus = function () {
    parent.inv.OpenPage("/cCheck/checkAdd", "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "<span class=\"menu-text\"> 新增盘点单 </span>\n" +
        "<b class=\"arrow \"></b>",true)
};
//
CCheck.refresh = function () {
    $('#cCheck_table').datagrid('unselectAll');
    CCheck.dtable.datagrid('reload');
};
//搜索
CCheck.search = function () {
    CCheck.dtable.datagrid('load', CCheck.sform.serializeObject());
};
CCheck.initGoodsTable = function(){
    $.ajax({
        type: "POST",
        url: "/sysDict/materiel_MU",
        dataType: "json",
        async: true,
        success: function (data) {
            CCheck.unitArr = data;
        }
    });

    var grid = new $yd.DataGrid(CCheck.goodsTable);
    grid.onDblClickRow = function (index,row) {
        CCheckDetail._edit(row['id']);
    };
    grid.rownumbers = true;
    grid.pagination = false;
    grid.url = CCheck.uEditDetail;
    grid.columns = [[
        {field: 'id', checkbox: false, hidden: true}
        , {field: 'skuId', hidden: true}
        , {field: 'positionId', hidden: true}
        , {field: 'goodsName', title: '商品名称', width: 80,halign:'center',align:'center'}
        , {field: 'skus', title: '规格', width: 100,halign:'center',align:'center'}
        , {field: 'skuCode', title: '商品编号', width: 80,halign:'center',align:'center'}
        , {
            field: 'unit', title: '单位', width: 80,halign:'center',align:'center', formatter: function (value, row, index) {
                for (var i = 0; i < CCheck.unitArr.length; i++) {
                    if (value == CCheck.unitArr[i].id) {
                        return CCheck.unitArr[i].text;
                    }
                }
                return value;
            }
        }
        // , {field: 'positionName', title: '库位', width: 80,halign:'center',align:'center'}
        // , {field: 'batchCode', title: '批次', width: 80}
        , {
            field: 'count', title: '库存数量', width: 80,halign:'center',align:'center',formatter: function (value, row) {
                if(CCheck.checkStatus != 0) {
                    return value;
                }
                if(Number(value) != Number(row.curNum)) {
                    return value + "（<span style='color:red'>" + row.curNum + "</span>）";
                } else {
                    return value;
                }
            }
        }
        , {field: 'curNum', title: '当前库存数量', width: 80,halign:'center',align:'center', hidden: true}
        , {
            field: 'checkCount',
            title: '<span style="color:blue">盘点数量</span>',
            width: 80,halign:'center',align:'center',
            editor: {type: 'numberbox', options: {required: true, min: 0, precision: 0}}
        }
        , {
            field: 'checkTotal', title: '盈亏数量', width: 80,halign:'center',align:'center', formatter: function (value, row) {
                var result = 0;
                if(CCheck.checkStatus == 0) {
                    result = Number(row['checkCount']) - Number(row['curNum']);
                } else {
                    result = Number(row['checkCount']) - Number(row['count']);
                }
                if (result > 0) {
                    return "<span style='color:blue'>" + result + "</span>"
                } else if (result < 0) {
                    return "<span style='color:red'>" + result + "</span>"
                } else {
                    return result;
                }
            }
        }
        , {field: 'remark', title: '<span style="color:blue">备注</span>', width: 80,halign:'center',align:'center', editor: {type: 'textbox'}}
    ]];
    grid.onClickCell = function (index, field) {
        if(CCheck.checkStatus != 0) {
            var eaRows = CCheck.goodsTable.datagrid('getRows');
            $(eaRows).each(function (index, item) {
                CCheck.goodsTable.datagrid('endEdit', index);
            });
            return;
        }
        if (CCheck.editIndex != index) {
            if (CCheck.editIndex > -1) {
                CCheck.goodsTable.datagrid('endEdit', CCheck.editIndex);
            }
            CCheck.editIndex = index;
        }
        if (field == "checkCount") {
            CCheck.goodsTable.datagrid('beginEdit', index);
        }
    };
    grid.onLoadSuccess = function () {
        if(CCheck.checkStatus == 0) {//未校正时才需要判断是否显示提示
            var rows = CCheck.goodsTable.datagrid("getRows");
            var isShow = 0;
            for(var i=0; i<rows.length; i++) {
                if(Number(rows[i].count) != Number(rows[i].curNum)) {
                    isShow = 1;
                    break;
                }
            }
            if(isShow == 1) {
                $("#tips").show();
            }
        }
    };
    grid.loadGrid();
    if(CCheck.checkStatus == 0) {
        CCheck.goodsTable.datagrid('enableCellEditing');
    }
};
CCheck.goodsTableBtn = function () {
    var sb = new $yd.SearchBtn($('#checkGoodsBtn'));
    if(CCheck.checkStatus == 0) {
        sb.create('check green', '校正库存', CCheck.correct);
    }
};
// 校正库存
CCheck.correct = function () {
    //结束编辑状态
    // if (CCheck.editIndex != undefined && CCheck.editIndex != -1) {
    //     CCheck.dtable.datagrid('endEdit', CCheck.editIndex);
    // }
    var eaRows = CCheck.goodsTable.datagrid('getRows');
    $(eaRows).each(function (index, item) {
        CCheck.goodsTable.datagrid('endEdit', index);
    });

    if (CCheck.checkStatus == 1) {
        $yd.alert("已经校正过");
        return;
    } else if (CCheck.checkStatus == 2) {
        $yd.alert("已作废无法校验");
        return;
    }
    $yd.confirm(function () {
        var rows = CCheck.goodsTable.datagrid("getRows");
        $.post("/cCheck/correct", {
            checkId: CCheck.checkId,
            details: JSON.stringify(rows)
        }, function (data) {
            if (data.message == "") {
                $yd.alert("操作成功", function () {
                    window.location.reload();
                });
            } else if(data.message == "notNew") {
                $yd.alert("当前库存不是最新，需要刷新页面", function () {
                    window.location.reload();
                });
            } else {
                $yd.alert(data.message);
            }
        });
    });
}

$(function () {
    CCheck.checkId = $("#checkId").val();
    CCheck.sform = $('#cCheck_form');
    CCheck.dtable = $('#cCheck_table');
    CCheck.obtn = '#cCheck_btn';
    CCheck.goodsTable = $('#checkGoods_table')
    CCheck.dg(); // 数据表格
    CCheck.btn(); // 初始化按钮
    CCheck.initGoodsTable();
    CCheck.goodsTableBtn();
    $yd.bindEnter(CCheck.search);
    new $yd.combotreegrid("#houseId").addCol("name", "名称").load("/wWearhouse/list");
});
var btn1 = document.getElementById("searchButton");
btn1.addEventListener("click", function() {
    $('#cCheck_table').datagrid('unselectAll');
    CCheck.dtable.datagrid('load', CCheck.sform.serializeObject());
});